<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="名称">
                <a-input allowClear placeholder="请输入名称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>

    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <div></div>

        <div>
          <a-button type="primary" icon="plus" @click="edit()">新建</a-button>
        </div>
      </div>
      <a-table
        :rowKey="
          (r, i) => {
            return r.id
          }
        "
        size="default"
        :columns="columns"
        :data-source="list"
        :customRow="customRow"
        :scroll="{ x: 'max-content' }"
        :pagination="{
          current: pageNo,
          pageSize,
          total,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
      >
        <span slot="name" slot-scope="text">
          <a-tooltip>
            <template slot="title"> {{ text }} </template>
            {{ text }}
          </a-tooltip>
        </span>

        <span slot="url" slot-scope="text">
          {{ text ? text.name + '-' + text.link : '' }}
        </span>

        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="edit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-button type="link" @click="handle('remove', record)" size="small">删除</a-button>
        </span>
      </a-table>

      <a-modal width="700px" v-model="visible" title="新建模版" ok-text="确认" cancel-text="取消" @ok="onSubmit">
        <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-model-item label="标题" prop="name">
            <a-input v-model="form.name" allowClear placeholder="请输入标题" />
          </a-form-model-item>
          <a-form-model-item label="链接" prop="url">
            <div class="flex">
              <a-input :value="form.url ? form.url.name : ''" disabled placeholder="请选择" />
              <a-button style="margin-left: 10px" type="primary" @click="showLink = true">选择</a-button>
            </div>
          </a-form-model-item>
          <a-form-model-item label="排序" prop="sort">
            <a-input-number v-model="form.sort" :min="0" :max="100" />
          </a-form-model-item>
          <a-form-model-item label="轮播图片" prop="pic_url">
            <cyyUploadImg
              @uploadSuccess="(e) => (form.pic_url = e.data)"
              @deleteImg="form.pic_url = ''"
              :imgSrc="form.pic_url"
              imgSizeText="750*360"
            >
            </cyyUploadImg>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </a-card>

    <select-link v-if="showLink" @onOk="onOk" @cancel="showLink = false" :isSingle="true"></select-link>
  </page-header-wrapper>
</template>

<script>
import { bannerList, bannerSave, bannerDel, list, listSelect } from '@/api/marketing/curPrice'
import { cyyUploadImg } from '@/components/CyyUi/index'
import SelectLink from '@/components/DiyNew/SelectLink/index.vue'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '标题',
    dataIndex: 'name',
    scopedSlots: {
      customRender: 'name',
    },
    ellipsis: true,
  },
  {
    title: '链接',
    dataIndex: 'url',
    scopedSlots: {
      customRender: 'url',
    },
  },
  {
    title: '排序',
    dataIndex: 'sort',
    sorter: (a, b) => parseFloat(a.sort) - parseFloat(b.sort),
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
    width: 200,
  },
]

export default {
  components: {
    cyyUploadImg,
    SelectLink,
  },
  data() {
    return {
      total: 0,
      pageNo: 1,
      pageSize: 10,
      columns,
      queryParam: {
        name: '',
      },
      list: [],
      visible: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },

      form: {
        name: '',
        sort: 50,
        url: null,
        pic_url: '',
      },

      rules: {
        name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
        pic_url: [{ required: true, message: '轮播图不能为空', trigger: 'blur' }],
        url: [{ required: true, message: '请选择', trigger: 'blur' }],
      },

      showLink: false,
    }
  },

  mounted() {
    this.getList()
  },

  watch: {
    visible(e) {
      if (!e) {
        this.resetForm()
      }
    },
  },

  methods: {
    onOk(e) {
      this.showLink = false
      this.form.url = e
    },

    async edit(item) {
      if (item) {
        let { id, name, sort, url, pic_url } = item

        this.form = {
          id,
          name,
          sort,
          url,
          pic_url,
        }
      } else {
        this.form = {
          name: '',
          sort: 50,
          url: null,
          pic_url: '',
        }
      }

      this.visible = true
    },

    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const hide = this.$message.loading('加载中', 0)
          let form = JSON.parse(JSON.stringify(this.form))
          form.url = JSON.stringify(form.url)

          const res = await bannerSave(form)
          hide()
          if (res.code == 0) {
            this.$message.success('创建成功')
            this.visible = false
            this.getList()

            this.form = {
              name: '',
              sort: 50,
              is_show: '1',
              url: null,
            }
            return
          }
          this.$message.error(res.msg)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    resetForm() {
      this.$refs.ruleForm.resetFields()
    },

    async getList(pageNo = 1) {
      const hide = this.$message.loading('加载中', 0)
      let { pageSize, queryParam } = this
      const res = await bannerList({
        pageSize,
        pageNo,
        ...queryParam,
      })
      if (res.code == 0) {
        this.pageNo = pageNo
        this.selectedRowKeys = []
        let { totalCount, list: data } = res.data

        data.forEach((el) => {
          if (el.url) {
            el.url = JSON.parse(el.url)
          }
        })
        this.total = totalCount
        this.list = data
      }
      hide()
    },

    tablePageChange(e) {
      this.getList(e)
    },

    handle(type, item) {
      switch (type) {
        case 'remove':
          this.remove(item.id)
          break
      }
    },

    remove(ids) {
      this.$confirm({
        title: '提示?',
        content: '是否删除？',
        onOk: () => {
          bannerDel({
            ids,
          }).then((res) => {
            if (res.code) {
              this.$error({
                content: res.msg,
              })
            } else {
              this.$message.success(res.msg)
              this.getList()
            }
          })
        },
        onCancel: () => {},
      })
    },
  },
}
</script>

<style lang="less" scoped>
.flex {
  display: flex;
}
</style>
